import fetch from 'dva/fetch';
import querystring from 'query-string';
import { message } from 'antd';

function detectError(data, response) {
  if (data.status=='error') {
    const error = new Error(data.message);
    error.response = response;
    throw error;
  }
}

export default async function request(url, options) {

  const GET_OR_HEAD = !options || (options && (options.method == 'GET' || options.method == '' || options.method == 'HEAD'));
  const HAS_BODY = options && options.body;

  // 接受 GET 方法传入 options.body
  if (GET_OR_HEAD && HAS_BODY) {
    url = [url, querystring.stringify(options.body)].join('&');
    delete options.body;
  }

  const hide = !GET_OR_HEAD && message.loading('正在请求...', 0);

  const response = await fetch(url, options);

  hide && hide();

  const data = await response.json();
  
  detectError(data, response);

  return data;
}